package main.java.com.leng.controller;

import com.leng.pojo.Book;
import com.leng.pojo.EasyUIDataGridResult;
import com.leng.pojo.User;
import com.leng.service.BookService;
import com.leng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by presoul on 2017/6/13.
 */
@Controller
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private UserService userService;
    @Autowired
    private HttpSession session;

    @RequestMapping("/bookList")
    public String getBookList(Model model,Integer page, double rows){

        EasyUIDataGridResult result = bookService.getAllbooks(page,rows);
         double  total=  (double)  result.getTotal();

        double pagesize = Math.ceil((total/rows));


       model.addAttribute("bookResult",result);
       model.addAttribute("page",page);
       model.addAttribute("pagesize",pagesize);
      return "bookList";
    }
    @RequestMapping(value = "/userLogin")
    public String adminLogin(String username,String password){

         User user = userService.findUserLogin(username,password);

         if (user.getUserName()!=null){

             session.setAttribute("user",user);

             return "userPage";
         }else {

             return "error";
         }
    }

    @RequestMapping("/userRent")
    @ResponseBody
    public List<Book> userRent(Integer id){
      return   bookService.getAllUserRentBook(bookService.getUserRent(id));
    }


    @RequestMapping("/rent")
    public String rent(Integer bookId,Integer userId){

        bookService.updateBookSum(bookId,userId);

        return "redirect:/bookList?page=1&rows=3";
    }

    @RequestMapping("/bookQuery")

    public String bookQuery(Model model,String queryDesc){

        EasyUIDataGridResult result = bookService.getAllQuerybooks(1,3,queryDesc);

        double  total=  (double)  result.getTotal();

        double pagesize = Math.ceil((total/3.0));


        model.addAttribute("bookResult",result);
        model.addAttribute("page",1);
        model.addAttribute("pagesize",pagesize);

        return "bookList";

    }
}
